class CalendarController < ApplicationController
  before_filter :login_required
  
  
  def index
  end
  
  def select_project
    p_id = params[:id]
    if p_id == nil || p_id == "undefined"
      @events = Calendar.find(:all, :conditions => "user_id=#{session['user']['id']}").sort_by {|c| if(c.date==nil) then [Date.today()] else [c.date] end}
        msg = 'Displaying all <b>your</b> events'
      else
        @events = Calendar.find(:all, :conditions => "project_id=#{p_id}").sort_by {|c| if(c.date==nil) then [Date.today()] else [c.date] end}
          msg = 'Displaying <b>project</b> events'
        end
        render(:partial=>'events', :locals=>{:msg=>msg})
      end
      
      def create
        c = Calendar.new(params['new'])
        c.project_id = -1 if params['new']['project_id'] == ''
        c.user_id = session['user']['id']
        c.save
        redirect_to(:action => 'index')
      end
      
      # Ajaxed
      def delete
        id = params[:id]
        t = Calendar.find(id)
        render_text '-1' and return if t == nil or (t.user_id != nil and t.user_id != session['user']['id']) # or (t.project_id) TODO: add something to verify if the event is on a project we are member of
        # t.user_id != nil so we can delete old events that had no user_id at the time of creation (old version of PTM)
        if Calendar.destroy(id)
          render_text "#{id}"
        else
          render_text '-1'
        end
      end
      
    end
